package com.android.antelopeapp.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.allthelucky.common.view.AutoPlayManager;
import com.allthelucky.common.view.ImageIndicatorView;
import com.allthelucky.common.view.ImageIndicatorView.OnItemClickListener;
import com.allthelucky.common.view.network.NetworkImageIndicatorView;
import com.android.antelopeapp.R;
import com.android.antelopeapp.activity.ActivityManager;
import com.android.antelopeapp.activity.BaseActivity;
import com.android.antelopeapp.constant.ApiConfig;
import com.android.antelopeapp.network.GsonRequest;
import com.android.antelopeapp.network.NetworkManager;
import com.android.antelopeapp.utils.NetworkUtils;
import com.android.antelopeapp.view.CNArticle.CNArticleListView;
import com.android.antelopeapp.bean.CNContent;
import com.android.antelopeapp.view.PtrHeader;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.lyhw.model.Article;
import com.lyhw.model.beanwraper.WraperFactory;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.indicator.PtrIndicator;

/**
 * @author phk
 * 精选页面
 * */
public class CNHomeFragment extends Fragment{
    public static final String TAG = "CNHomeFragment";
	/**
	 * 自动轮播组件
	 * */
	private NetworkImageIndicatorView autoImageIndicatorView;
	private AutoPlayManager autoBrocastManager;
	private CNArticleListView listView;
    private List<Article> topArticles;
    private PtrClassicFrameLayout pullToRefresh;
	
	@Override
	public View onCreateView( LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_cn_home, container,false);
        listView = (CNArticleListView) rootView.findViewById(R.id.content_list);
        //设置头部轮播组件
        this.autoImageIndicatorView = (NetworkImageIndicatorView)inflater.inflate(R.layout.view_cn_indicator,null,false);
        listView.addHeaderView(this.autoImageIndicatorView);
        //初始化可下拉自动添加文章的listview
        if(this.getActivity() instanceof  BaseActivity) {
            //指定用于listview的item样式
            listView.init((BaseActivity) this.getActivity(),R.layout.view_cn_content_item);
        }else{
            Log.e(TAG,"init CNArticleListView failed");
        }
        //按创建时间逆序排列
        getHeaderContent();

        //使fragment恢复状态时跳过oncreate
        setRetainInstance(true);
	    //
        pullToRefresh=(PtrClassicFrameLayout)rootView.findViewById(R.id.ptr_to_rfresh);
        pullToRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view2) {
                return PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, view, view2);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                ptrFrameLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //数据更新，待写
                        if(topArticles==null){
                            Log.v("header",autoImageIndicatorView.getChildCount()+"");
                            getHeaderContent();
                        }
                        listView.refreshListView();
                        pullToRefresh.refreshComplete();

                    }
                },1800);
            }
        });
        pullToRefresh.setLastUpdateTimeKey("");
		return rootView;
	}

    private void getHeaderContent(){
        String url = ApiConfig.REQUEST_TOP_ARTICLE_LIST;

        GsonRequest<WraperFactory.ArticleWraper> gsonRequest = new GsonRequest<WraperFactory.ArticleWraper>(url,
                WraperFactory.ArticleWraper.class,
                null,
                new Response.Listener<WraperFactory.ArticleWraper>() {
                    @Override
                    public void onResponse(WraperFactory.ArticleWraper response) {
                        List<String> urlList = new ArrayList<>();
                        topArticles = response.getData();
                        for(Article article:topArticles){
                            urlList.add(article.getMainpic());
                        }
                        //初始化内部view
                        initIndicatorView();
                        //执行轮播
                        runIndicator(urlList);

                        listView.deferNotifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d(CNHomeFragment.this.getClass().getName(),"获取top列表失败");
                    }
                });
        NetworkManager.getInstance(this.getActivity()).getRequestQueue().add(gsonRequest);
    }
	
	@Override
	public void onDetach() {
		super.onDetach();
        Log.v("lifecycle","detach get");
		pauseIndicator();
	}
	
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
        resumeIndicator();
	}

    /**
    @Override
    public void onResume() {
        super.onResume();
        Log.v("lifecycle","resume get");
        if(!NetworkUtils.isNetworkConnected(this.getActivity())){
            //未联网
            listView.setVisibility(View.GONE);
            ((BaseActivity)getActivity()).sendToastMsg("网络未连接");
        }else{
            listView.setVisibility(View.VISIBLE);
        }
    }

    public void reJudgeNetwork(){
        if(!NetworkUtils.isNetworkConnected(this.getActivity())){
            ((BaseActivity)getActivity()).sendToastMsg("网络未连接");
        }else{
            listView.setVisibility(View.VISIBLE);
        }
    }
    **/

    /**
	 * 测试获取精选内容
	 * */
	public static  List<CNContent>  getTestData() {
		List<CNContent>  list = new ArrayList<CNContent>();
		//测试
		list.add(new CNContent("错误", 1, "网络连接出错",null));
        list.add(new CNContent("错误", 1, "网络连接出错",null));
        list.add(new CNContent("错误", 1, "网络连接出错",null));
        list.add(new CNContent("错误", 1, "网络连接出错",null));
		return list;
	}

	/**
	 * 初始化轮播组件
	 * */
	private void initIndicatorView( ) {
		//this.autoImageIndicatorView = (ImageIndicatorView) preView.findViewById(R.id.indicate_view);
		
		autoImageIndicatorView.setOnItemChangeListener(new ImageIndicatorView.OnItemChangeListener() {
			@Override
			public void onPosition(int position, int totalCount) {
				Log.v("ImageIndicatorView", "OnItemChangeListener pos="+position+" totcnt="+totalCount);
			}
		});
		
		autoImageIndicatorView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void OnItemClick(View view, int position) {
                ActivityManager.startReArticleDetailActivity(CNHomeFragment.this.getActivity(), topArticles.get(position).getId());
				Log.v("ImageIndicatorView", "OnItemClickListener view="+view+" pos="+position);
			}
		});
		
		//不显示左右移动的箭头
		this.autoImageIndicatorView.setIndicateStyle(ImageIndicatorView.INDICATE_USERGUIDE_STYLE);
	}

	/**
	 * 开始执行轮播
	 * */
	private boolean runIndicator(List<String> urlList){
		if(autoImageIndicatorView == null){
			return false;
		}
        // 从本地获取内容
//		final Integer[] resArray = new Integer[] { R.drawable.indicate_img_1,  R.drawable.indicate_img_2, R.drawable.indicate_img_3,
//				 R.drawable.indicate_img_4};
		this.autoImageIndicatorView.setupLayoutByImageUrl(urlList);
		this.autoImageIndicatorView.show();

        AutoPlayManager autoBrocastManager =  new AutoPlayManager(this.autoImageIndicatorView);
        autoBrocastManager.setBroadcastEnable(true);
        autoBrocastManager.setBroadCastTimes(5);//loop times
        autoBrocastManager.setBroadcastTimeIntevel(3 * 1000, 3 * 1000);//set first play time and interval
        autoBrocastManager.loop();
		/*
		autoBrocastManager =  new AutoPlayManager(this.autoImageIndicatorView);
		autoBrocastManager.setMoveStyle(AutoPlayManager.MOVE_STYLE_RIGHT_FORVER);
		autoBrocastManager.setBroadcastEnable(true);
		autoBrocastManager.setBroadCastTimes(20);//循环次数
		autoBrocastManager.setBroadcastTimeIntevel(3 * 1000, 3 * 1000);//首次启动时间及间隔
		autoBrocastManager.loop();
		*/
		return true;
	}
	
	private void resumeIndicator(){
		if(autoBrocastManager != null){
			autoBrocastManager.setBroadcastEnable(true);
			autoBrocastManager.loop();
		}
	}
	
	/**
	 * 暂停轮播
	 * */
	private void pauseIndicator(){
		if(autoBrocastManager != null){
			autoBrocastManager.setBroadcastEnable(false);
		}
	}
}
